#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
启动API服务器2 - 专门接收boss_node发送的分析结果
"""

import uvicorn
import os
import sys

# 添加项目路径
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from fastapi import FastAPI, Request
from fastapi.responses import JSONResponse
from typing import Dict, Any
from datetime import datetime
import os

# 导入自定义模块
from agent_mcp.confidence_module.confidence_analyzer import ConfidenceAnalyzer
from agent_mcp.role.rule_engine import RuleEngine
from agent_mcp.llm.llm_analyzer import LLMAnalyzer

# 创建FastAPI应用
app = FastAPI(
    title="Agent MCP API Server 2",
    description="专门接收boss_node分析结果的API服务器",
    version="1.0.0"
)

@app.get("/")
async def root():
    """根路径"""
    return {
        "message": "Agent MCP API Server 2 正在运行",
        "version": "1.0.0",
        "endpoints": {
            "llm_analysis": "/api/intelligent/process_llm_analysis"
        }
    }

@app.get("/health")
async def health_check():
    """健康检查"""
    return {"status": "healthy", "service": "agent_mcp_api_server2"}

# POST路由，用于处理boss_node发送的LLM分析结果
@app.post("/api/intelligent/process_llm_analysis")
async def process_llm_analysis(request: Request):
    try:
        # 异步获取请求中的JSON数据
        data = await request.json()

        # 检查传过来的JSON数据格式
        if "analysis_result" not in data:
            return JSONResponse({
                "success": False,
                "error": "缺少analysis_result字段"
            }, status_code=400)

        analysis_result = data["analysis_result"]
        
        # 1. 异常分类和总结分析
        anomaly_summary = await analyze_anomalies(analysis_result)
        
        # 2. 置信度分析
        # 创建ConfidenceAnalyzer实例，设置阈值为0.7
        # 初始化confidence_results列表用于存储置信度分析结果
        confidence_analyzer = ConfidenceAnalyzer(threshold=0.7)
        confidence_results = []

        # 遍历所有异常，对每个异常进行置信度分析
        # 计算置信度分数和等级，并将结果添加到 confidence_results 列表中
        for anomaly in anomaly_summary["anomalies"]:
            confidence_score = confidence_analyzer.analyze_confidence(anomaly)
            confidence_level = confidence_analyzer.get_confidence_level(confidence_score)
            confidence_results.append({
                "anomaly_id": anomaly["anomaly_id"],
                "confidence_score": confidence_score,
                "confidence_level": confidence_level,
                "anomaly_data": anomaly
            })
        
        # 3. 分支处理
        # 生成时间戳并创建Ansible目录路径
        # 使用 os.makedirs 创建目录，exist_ok=True 表示如果目录已存在不会报错
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        ansible_dir = f"agent-mcp/Ansible/{timestamp}"
        os.makedirs(ansible_dir, exist_ok=True)

        # 初始化两个列表用于存储规则引擎和LLM分析的结果
        rule_engine_results = []
        llm_results = []
        
        print(f"=== 开始处理 {len(confidence_results)} 个异常 ===")

        # 遍历所有置信度分析结果，使用 enumerate 获取索引（从1开始）
        # 提取异常ID、置信度分数和异常数据
        for i, result in enumerate(confidence_results, 1):
            anomaly_id = result["anomaly_id"]
            confidence_score = result["confidence_score"]
            anomaly_data = result["anomaly_data"]
            
            print(f"\n处理异常 {i}: {anomaly_id}")
            print(f"置信度分数: {confidence_score:.3f}")
            print(f"置信度等级: {result['confidence_level']}")
            
            if confidence_score >= 0.7:
                # 分支一：置信度>=0.7，使用规则引擎
                print(f"置信度>=0.7，使用规则引擎处理...")
                try:
                    rule_engine = RuleEngine()
                    rule_result = await rule_engine.process_anomaly(
                        anomaly_data, 
                        ansible_dir
                    )
                    rule_engine_results.append(rule_result)
                    print(f"规则引擎处理结果: {rule_result.get('success', False)}")
                    if rule_result.get('success'):
                        print(f"选择的脚本: {rule_result.get('selected_script', 'N/A')}")
                except Exception as e:
                    print(f"规则引擎处理异常: {e}")
                    rule_engine_results.append({
                        "success": False,
                        "error": str(e),
                        "anomaly_id": anomaly_id,
                        "processing_method": "rule_engine"
                    })
            else:
                # 分支二：置信度<0.7，使用LLM分析
                print(f"置信度<0.7，使用LLM分析处理...")
                try:
                    llm_analyzer = LLMAnalyzer(confidence_threshold=0.8)
                    llm_result = await llm_analyzer.process_anomaly(
                        anomaly_data, 
                        ansible_dir
                    )
                    llm_results.append(llm_result)
                    print(f"LLM分析处理结果: {llm_result.get('success', False)}")
                    if llm_result.get('success'):
                        print(f"生成的脚本: {llm_result.get('generated_script', 'N/A')}")
                except Exception as e:
                    print(f"LLM分析处理异常: {e}")
                    llm_results.append({
                        "success": False,
                        "error": str(e),
                        "anomaly_id": anomaly_id,
                        "processing_method": "llm_analysis"
                    })
        
        print(f"\n=== 处理完成 ===")
        print(f"规则引擎处理: {len(rule_engine_results)} 个")
        print(f"LLM分析处理: {len(llm_results)} 个")

        # 返回处理成功的JSON响应，包含时间戳、Ansible目录、置信度分析结果、规则引擎结果、LLM分析结果和摘要信息
        return JSONResponse({
            "success": True,
            "timestamp": timestamp,
            "ansible_directory": ansible_dir,
            "confidence_analysis": confidence_results,
            "rule_engine_results": rule_engine_results,
            "llm_results": llm_results,
            "summary": {
                "total_anomalies": len(confidence_results),
                "rule_engine_processed": len(rule_engine_results),
                "llm_processed": len(llm_results)
            }
        })

    except Exception as e:
        print(f"API处理异常: {e}")
        return JSONResponse({
            "success": False,
            "error": str(e)
        }, status_code=500)

# 定义异步函数 analyze_anomalies，接收分析结果并返回异常摘要
# 添加了类型提示，参数为字典类型，返回值也是字典类型
async def analyze_anomalies(analysis_result: Dict[str, Any]) -> Dict[str, Any]:
    """分析异常指标并进行分类"""
    
    anomalies = []
    
    # 处理anomaly_analysis中的每个异常
    for anomaly in analysis_result.get("anomaly_analysis", []):
        anomaly_data = {
            #id 问题类型 根本原因 严重性 贡献因子 证据
            "anomaly_id": anomaly.get("anomaly_id"),
            "issue_type": anomaly.get("analysis", {}).get("issue_type"),
            "root_cause": anomaly.get("analysis", {}).get("root_cause"),
            "severity": anomaly.get("analysis", {}).get("severity"),
            "contributing_factors": anomaly.get("analysis", {}).get("contributing_factors", []),
            "evidence": anomaly.get("analysis", {}).get("evidence", [])
        }
        anomalies.append(anomaly_data)
    
    # 处理overall_assessment
    overall = analysis_result.get("overall_assessment", {})
    overall_data = {
        # 主要问题 根本原因 严重程度 业务影响 预计解决时间
        "primary_issue": overall.get("primary_issue"),
        "root_cause": overall.get("root_cause"),
        "severity_level": overall.get("severity_level"),
        "business_impact": overall.get("business_impact"),
        "estimated_resolution_time": overall.get("estimated_resolution_time")
    }
    
    return {
        # 异常列表 评估结果 推荐措施 受影响业务
        "anomalies": anomalies,
        "overall_assessment": overall_data,
        "recommendations": analysis_result.get("recommendations", {}),
        "affected_services": analysis_result.get("affected_services_summary", {})
    }

if __name__ == "__main__":
    print("=== 启动Agent MCP API Server 2 ===")
    print("服务器地址: http://localhost:8001")
    print("API文档: http://localhost:8001/docs")
    print("健康检查: http://localhost:8001/health")
    print("LLM分析端点: http://localhost:8001/api/intelligent/process_llm_analysis")
    print("\n按 Ctrl+C 停止服务器")

    # 启动服务器
    uvicorn.run(
        "start_api_server2:app",
        host="0.0.0.0",
        port=8001,
        reload=True,
        log_level="info"
    )

# def start_api_server2_1():
#     print("=== 启动Agent MCP API Server 2 ===")
#     print("服务器地址: http://localhost:8001")
#     print("API文档: http://localhost:8001/docs")
#     print("健康检查: http://localhost:8001/health")
#     print("LLM分析端点: http://localhost:8001/api/intelligent/process_llm_analysis")
#     print("\n按 Ctrl+C 停止服务器")
#
#     # 启动服务器
#     uvicorn.run(
#         "start_api_server2:app",
#         host="0.0.0.0",
#         port=8001,
#         reload=True,
#         log_level="info"
#     )